/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.tukano.misc;

import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;

/**
 * Table cell editor for a Term instance
 * @author utente4
 */
public class TermTableCellEditor extends AbstractCellEditor implements TableCellEditor {
    
    //Default serial version code
    private static final long serialVersionUID = 0;
    
    private JTable table;
    private int row, col;
    private final TermEditor editor = new TermEditor();
    private Term editedValue = null;
    private JPopupMenu popup;
    private final JLabel label = new JLabel("");
    private final Runnable onAccept = new Runnable() {

        public void run() {
            editedValue = editor.getEditorValue();
            table.setValueAt(editedValue, row, col);
            fireEditingStopped();
        }
    };
    private final Runnable onCancel = new Runnable() {

        public void run() {
            fireEditingCanceled();
        }
    };
    

    public TermTableCellEditor() {
    }

    public Object getCellEditorValue() {
        return editedValue;
    }

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        this.table = table;
        this.row = row;
        this.col = column;
        editedValue = (Term) value;
        editor.setEditorValue(editedValue);
        final Rectangle area = table.getCellRect(row, column, false);
        popup = editor.popup(table, area.getLocation(), onAccept, onCancel);
        return null;
    }

    @Override
    public boolean isCellEditable(EventObject e) {
        if(e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent) e;
            return me.getClickCount() == 2;
        } else if(e instanceof KeyEvent) {
            KeyEvent ke = (KeyEvent) e;
            int code = ke.getKeyCode();
            return ke.getID() == KeyEvent.KEY_PRESSED && (code != KeyEvent.VK_ENTER && code != KeyEvent.VK_TAB);
        } else {
            return false;
        }
    }

    @Override
    public void cancelCellEditing() {
        if(popup != null) popup.setVisible(false);
        super.cancelCellEditing();
    }

    @Override
    public boolean stopCellEditing() {
        editedValue = editor.getEditorValue();
        return super.stopCellEditing();
    }
}
